#!/bin/bash

# 设置你的Java应用的jar文件路径
APP_JAR="keller-server-2.0.1.jar"

# 设置Java应用的进程名称（通常就是jar包的名字，不包括.jar后缀）
APP_NAME="keller-server"

# 默认配置文件路径，可以根据传入的参数覆盖
CONFIG_FILE="resources/application-prod.yml"

# 获取第一个参数
ACTION=$1
# 获取第二个参数作为配置文件路径（如果提供）
if [ ! -z "$2" ]; then
    CONFIG_FILE="$2"
fi

function start_app() {
    echo "Starting $APP_NAME with config $CONFIG_FILE..."
    nohup java -Dspring.config.location="$CONFIG_FILE" -jar "$APP_JAR" > "$APP_NAME".log 2>&1 &
    echo "$APP_NAME started with $CONFIG_FILE."
}

function stop_app() {
    echo "Stopping $APP_NAME..."
    kill -9 $(pgrep -f "$APP_JAR")
    sleep 5
    if pgrep -f "$APP_JAR" > /dev/null; then
        echo "Warning: $APP_NAME process could not be stopped, please check manually."
    else
        echo "$APP_NAME stopped successfully."
    fi
}

case $ACTION in
    start)
        start_app "$CONFIG_FILE"
        ;;
    stop)
        stop_app
        ;;
    restart)
        stop_app
        sleep 5

        start_app "$CONFIG_FILE"
        ;;
    *)
        echo "Usage: $0 {start|stop|restart} [config_path]"
        exit 1
        ;;
esac

exit 0
